package com.jzo2o.foundations.handler;

import com.jzo2o.api.foundations.dto.response.RegionSimpleResDTO;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.service.IRegionService;
import com.jzo2o.foundations.service.IServeService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class SpringCacheSynHandler {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IRegionService regionService;
    @Autowired
    private IServeService serveService;

    //todo 要整理
    //最开始失效是父工程中没有管理public依赖
    //每天凌晨更新相关缓存的方法
    @XxlJob("activeRegionCacheSync")
    public void activeRegionCacheSync() {
        log.info("开始定时更新 区域列表缓存");
        //删除缓存
        redisTemplate.delete(RedisConstants.CacheName.JZ_CACHE+"::ACTIVE_REGIONS");
        //查询一次，在保存到缓存
        List<RegionSimpleResDTO> regionSimpleResDTOS = regionService.queryActiveRegionListCache();
        //首页服务列表缓存更新
        log.info("开始定时更新 首页服务列表缓存");
        for (RegionSimpleResDTO regionSimpleResDTO : regionSimpleResDTOS) {
            //拿到当前区域id
            Long id = regionSimpleResDTO.getId();
            //删除缓存
            redisTemplate.delete(RedisConstants.CacheName.SERVE_ICON+"::"+id);
            //更新缓存
            serveService.firstPageServeList(id);

            log.info("开始定时更新 热门服务列表缓存");
            //删除热门服务缓存-区域不止一个，因此也需要遍历区域列表，可以合并到区域首页服务列表中
            redisTemplate.delete(RedisConstants.CacheName.HOT_SERVE+"::"+id);
            //查询区域热门服务-保存缓存
            serveService.hotServeList(id);
        }

    }
}
